package com.agan.redis.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;
import java.util.concurrent.TimeUnit;


/**
 * 抢红包实例
 */
@RestController
@RequestMapping
public class RedpacketConrtoller {

    private static final String RED_PACKET_CONSUME_KEY ="redpacket：consume:";
    private static final String ID_KEY = "red:packet";
    private static final String RED_PACKET_KEY= "redpacket:";
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 抢红包
     */
    @GetMapping
    public int rob(long redid,long userid){
        //验证该用户是否已经抢过
        Object packet = redisTemplate.opsForHash().get(RED_PACKET_CONSUME_KEY + redid, String.valueOf(userid));
        if (packet == null){
            Object o = redisTemplate.opsForList().leftPop(RED_PACKET_KEY + redid);
            if (o!=null){
                redisTemplate.opsForHash().put(RED_PACKET_CONSUME_KEY+redid,String.valueOf(userid),o);
                return (Integer) o;
            }
            //表示已经抢完
            return -1;
        }
        //表示已抢过
        return -2;
    }

    /**
     * 设置红包
     */
    @GetMapping("set")
    public long setRedpacket(int total,int count){
        Integer[] packets = this.splitRedPacket(total, count);
        //生成红包的全局唯一id
        Long aLong = this.incrementId();
        String key =  RED_PACKET_KEY+ aLong;
        redisTemplate.opsForList().leftPushAll(key,packets);
        redisTemplate.expire(key,3,TimeUnit.DAYS);
        return aLong;
    }


    /**
     * 生成全局唯一id
     */
    public Long incrementId(){
        Long increment = this.redisTemplate.opsForValue().increment(ID_KEY);
        return increment;
    }

    /**
     * 拆解红包
     * @param total
     * @param count
     * @return
     */
    public Integer[] splitRedPacket(int total,int count){
        int use =0;
        Integer[] arrays = new Integer[count];
        Random random = new Random();
        for (int i = 0; i < count; i++) {
            if (i==count-1){
                arrays[i] =total - use;
            }else {
                int avg =(total-use)*2/(count - i);
                arrays[i] =1+random.nextInt(avg-1);
            }
            use = use +arrays[i];
        }
        return arrays;
    }



}



